import { message } from 'antd';
import { updateSysUser, addSysUser, updateSysUserStatus, querySysUserList, getSysUserInfo, queryRoleList } from '../services/api';

export default {
  namespace: 'sysUser',

  state: {
    managerInfo: {},
    adminList: [],
    roleList: [],
    sysUserList: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(querySysUserList, payload);
      yield put({
        type: 'sysUserList',
        payload: response,
      });
    },
    *add({ payload, callback }, { call, _ }) {
      const response = yield call(addSysUser, payload);
      if (response.code === 0) {
        message.success('添加成功');
        if (callback) callback();
      } else {
        message.error('添加失败');
      }
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateSysUser, payload);
      if (response.code === 0) {
        if (callback) callback();
        message.success('修改成功');
      } else {
        message.error('修改失败');
      }
    },
    *updateStatus({ payload, callback }, { call }) {
      const response = yield call(updateSysUserStatus, payload);
      if (response.code === 0) {
        message.success('修改成功');
        if (callback) callback();
      } else {
        message.error('修改失败');
      }
    },
    *info({ payload }, { call, put }) {
      const response = yield call(getSysUserInfo, payload);
      yield put({
        type: 'managerDetail',
        payload: response,
      });
    },
    *roleList({ payload }, { call, put }) {
      const response = yield call(queryRoleList, payload);
      yield put({
        type: 'roleLists',
        payload: response,
      });
    },
  },

  reducers: {
    managerDetail(state, action) {
      return {
        ...state,
        managerInfo: action.payload.data,
      };
    },
    adminLists(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    roleLists(state, action) {
      return {
        ...state,
        roleList: action.payload.data,
      };
    },
    sysUserList(state, action) {
      return {
        ...state,
        sysUserList: action.payload.data,
      };
    },
  },
};
